package servlet;

import dao.BaseDao;
import eneity.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class loginServlet extends HttpServlet {
    User user=new User();
    BaseDao baseDao=new BaseDao();
    PreparedStatement pstmt=null;
    ResultSet resultSet=null;
    Connection connection=null;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        user.setPassword(req.getParameter("username"));
        user.setUsername(req.getParameter("password"));
        String sql="SELECT * FROM news_users WHERE uname=? AND  upwd=?;";
        Object[] objs={user.getUsername(),user.getPassword()};
        connection=baseDao.getConnByJNDI();
        pstmt=baseDao.pstmt(connection,sql,objs);
        try {
            resultSet=pstmt.executeQuery();
            if (resultSet.next()){
                req.getSession().setAttribute("username",user.getUsername());
                req.getSession().setAttribute("password",user.getPassword());
                req.getSession().setAttribute("isLogin",true);
                req.getRequestDispatcher("topicInfoServlet").forward(req,resp);
            }
            else{
                req.getSession().setAttribute("isLogin",false);
                resp.sendRedirect("index.jsp");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
